package com.remoter.transport.netty.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import com.remoter.api.protocol.support.RemoterRequest;
import com.remoter.api.protocol.support.RemoterResponse;
import com.remoter.api.provider.IProviderService;
import com.remoter.api.transport.IMessageTask;
import com.remoter.api.transport.IMessageTaskCallBack;
import com.remoter.transport.netty.task.NettyServerMessageTask;
import com.remoter.transport.netty.task.NettyServerMessageTaskCallBack;

public class ServerMessageHandler extends ChannelInboundHandlerAdapter{
	
	private IProviderService provider;
	
	public ServerMessageHandler(IProviderService provider){
		this.provider = provider;
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {
		if(null != msg && msg instanceof RemoterRequest){
			RemoterRequest remoterRequest = (RemoterRequest)msg;
			RemoterResponse remoterResponse = new RemoterResponse(remoterRequest.getToken());
			IMessageTask messageTask = new NettyServerMessageTask(remoterRequest,remoterResponse);
			IMessageTaskCallBack messageTaskCallBack = new NettyServerMessageTaskCallBack(remoterRequest,remoterResponse,ctx);
			this.provider.submit(messageTask,messageTaskCallBack);
		}
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {
		ctx.close();
	}
	
}